package com.cote.douhahou.pretloan.any.util

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.adjust.sdk.*
import com.cote.douhahou.pretloan.beans.AakomapalendPamadjustInst
import com.cote.douhahou.pretloan.any.event.AkomapalendIAnalyticsEvent
import com.cote.douhahou.pretloan.any.http.AkomapalendHttpHelper
import com.cote.douhahou.pretloan.utils.AkomapaLendConfigs
import com.cote.douhahou.pretloan.utils.AkomapaLendConfigs.AdjustEventApply
import com.cote.douhahou.pretloan.utils.AkomapaLendConfigs.AdjustEventREGISTER
import com.cote.douhahou.pretloan.utils.AkomapaLendConfigs.AdjustToken
import com.cote.douhahou.pretloan.url.AkomapalendPaths
import com.cote.douhahou.pretloan.utils.AkomapaLendUtil

object AkomapalendAdjustUtil {

    var adjsutAttribution_akomapalend: AakomapalendPamadjustInst? = null

    /**
     * @param context Application
     */
    fun init(context: Application) {
        if (AdjustToken.isBlank()) throw Exception("Error: Adjust Token must no be null!")
        if (AdjustEventREGISTER.isBlank()) throw Exception("Error: Adjust Register code must no be null!")
        if (AdjustEventApply.isBlank()) throw Exception("Error: Adjust Apply code must no be null!")

        val config = AdjustConfig(context, AdjustToken, AkomapaLendConfigs.AdjustEnviroment)
        
        config.setLogLevel(LogLevel.INFO)

        config.setOnAttributionChangedListener { covertAndSaveAttributtion(it) }
        
        Adjust.onCreate(config)

        registerAdjustActivityLifecycle(context)

        val attribution = Adjust.getAttribution()
        covertAndSaveAttributtion(attribution)
    }

    /**
     * @param attribution AdjustAttribution
     */
    private fun covertAndSaveAttributtion(attribution: AdjustAttribution?) {
        attribution?.let { result ->
            //组装
            adjsutAttribution_akomapalend = AakomapalendPamadjustInst()

            //adjust 归因参数
            adjsutAttribution_akomapalend?.let { params ->
                params.adid = result.adid.orEmpty()
                params.network = result.network.orEmpty()
                params.adgroup = result.adgroup.orEmpty()
                params.creative = result.creative.orEmpty()
                params.costType = result.costType.orEmpty()
                params.campaign = result.campaign.orEmpty()
                params.clickLabel = result.clickLabel.orEmpty()
                params.trackerName = result.trackerName.orEmpty()
                params.trackerToken = result.trackerToken.orEmpty()
                params.costCurrency = result.costCurrency.orEmpty()
                params.fbInstallReferrer = result.fbInstallReferrer.orEmpty()
                result.costAmount?.let { costAmount ->
                    params.costAmount = costAmount.toString()
                }
                
                println("=====adjust attribution:")
                println(result)

                val pathList = mutableListOf(
                    AkomapaLendUtil.commonUrl()
                )
                saveInstallInfo(pathList)
            }
        }
    }

    /**
     * @param context Application
     */
    fun registerAdjustActivityLifecycle(context: Application) {
        context.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(p0: Activity, p1: Bundle?) {
            }

            override fun onActivityStarted(p0: Activity) {
            }

            override fun onActivityResumed(p0: Activity) {
                Adjust.onResume()
            }

            override fun onActivityPaused(p0: Activity) {
                Adjust.onPause()
            }

            override fun onActivityStopped(p0: Activity) {
            }

            override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
            }

            override fun onActivityDestroyed(p0: Activity) {
            }
        })
    }

    fun addEvent(event: AkomapalendIAnalyticsEvent) {
        try {
            when (event) {
                AkomapalendIAnalyticsEvent.AT_REGISTER -> {
                    Adjust.trackEvent(AdjustEvent(AdjustEventREGISTER))
                }
                AkomapalendIAnalyticsEvent.AT_LOAN_APPLY -> {
                    Adjust.trackEvent(AdjustEvent(AdjustEventApply))
                }
                else -> {}
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun saveInstallInfo(targetUrlList: List<String>) {
        adjsutAttribution_akomapalend?.let { data ->
            try {
               val body = data.toEncryptParams(AkomapalendPaths.PATH_ADJUST_INSTALL)
//                val body = Gson().toJson(adjsutAttribution).trim()
                println("====== $targetUrlList")

                val apiPath = AkomapaLendUtil.commonUrl()
                targetUrlList.forEach { host ->
                    val pathFormat =
                        if (host.endsWith(apiPath)) host else (host + apiPath)
                    AkomapalendHttpHelper.postData(pathFormat, body)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}